package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.common.ApThreadLocalUtil;
import com.mongodb.client.result.DeleteResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Resource
    private MongoTemplate mongoTemplate;
    /**
     * 保存用户搜索历史记录
     *
     * @param keyword
     * @param userId
     */
    @Override
    @Async
    public void insert(String keyword, Integer userId) {
        // 1,搜索关键词,判断是否存在
        Query query = Query.query(
                Criteria.where("keyword").in(keyword).and("userId").is(userId)
        );
        ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);
        // 已存在
        if(apUserSearch != null){
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
            return;
        }
        // 修改已存在的数据时间
        apUserSearch = new ApUserSearch();
        apUserSearch.setUserId(userId);
        apUserSearch.setKeyword(keyword);
        apUserSearch.setCreatedTime(new Date());
        // 查看是否满足10条
        List<ApUserSearch> apUserSearches = mongoTemplate.find(
                Query.query(
                        Criteria.where("userId").is(userId)
                ).with(Sort.by(Sort.Direction.DESC, "createdTime")),
                ApUserSearch.class
        );
        if(apUserSearches != null && apUserSearches.size()<10){
            // 记录小于10条就新增
            mongoTemplate.insert(apUserSearch);
        }else{
            ApUserSearch search = apUserSearches.get(apUserSearches.size() - 1);
            // 大于10条就修改最旧的数据
            mongoTemplate.findAndReplace(
                    Query.query(Criteria.where("_id").is(search.getId())),apUserSearch
            );
        }
    }

    /**
     * 载入搜索列表
     */
    @Override
    public ResponseResult load() {
        // 判断是否登录
        ApUser apUser = ApThreadLocalUtil.getApUser();

        log.info("===={}",apUser);

        if(apUser == null && apUser.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 根据用户id查询历史搜索记录
        Query query = Query.query(
                Criteria.where("userId").is(apUser.getId())
        );
        query.with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApUserSearch> searchList = mongoTemplate.find(query, ApUserSearch.class);

        return ResponseResult.okResult(searchList);
    }
    /**
     * 删除
     */
    @Override
    public ResponseResult delHistory(HistorySearchDto dto) {
        if(dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 1,搜索关键词,判断是否存在
        ApUser apUser = ApThreadLocalUtil.getApUser();
        if(apUser == null && apUser.getId() != null ){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        Query query = Query.query(
                Criteria.where("_id").is(dto.getId()).and("userId").is(apUser.getId())
        );
        DeleteResult remove = mongoTemplate.remove(query, ApUserSearch.class);
        boolean b = remove.wasAcknowledged();
        return ResponseResult.okResult(b ? "成功" : "失败");
    }
}
